//新增实例案例

<template>
    <div class="new-p">
        <div class="header">
            <span>新增实例案例</span>
            <el-button type="warning" @click="Back" style="width:100px">返回</el-button>
        </div>
        <div class="line"></div>
        <el-form :model="test" label-width="120px" style="margin:50px 0;padding: 20px;" :rules="rules"
            ref="ruleFormRef">
            <el-form-item label="实例标题" prop="title">
                <el-input v-model="test.title" placeholder="请输入实例标题" style="width:500px" size="large" />
            </el-form-item>
            <!--图片上传 -->
            <el-form-item label="上传配图">
                <el-upload class="avatar-uploader" :auto-upload="false" :on-change="upload" list-type="picture-card">
                    <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus />
                    </el-icon>
                </el-upload>
                <span style="margin:20px">上传图片不要超过2M</span>
            </el-form-item>


            <el-form-item label="实例简介" prop="intro">
                <el-input v-model="test.intro" placeholder="请输入实例简介不要超过300字，显示在二级列表页" type="textarea" rows="8" />
            </el-form-item>
            <el-form-item label="推荐至首页" prop="change">
                <el-select v-model="test.change" placeholder="请选择">
                    <el-option label="是" value="是" />
                    <el-option label="否" value="否" />
                </el-select>
            </el-form-item>
            <el-form-item label="排序位" prop="number">
                <el-input v-model="test.number" placeholder="0" style="width:300px" />
            </el-form-item>
            <el-form-item label="实例详情">

                <!-- 富文本插件 -->
                <div style="border: 2px solid #ccc;width: 900px;height: 300px;">
                    <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig"
                        :mode="mode" />
                    <Editor style="height: 500px; overflow-y: hidden;" v-model="valueHtml" :defaultConfig="editorConfig"
                        :mode="mode" @onCreated="handleCreated" />
                </div>


            </el-form-item>
            <el-form-item>
                <el-button type="warning" @click="onSubmit(ruleFormRef)" style="width:150px;height: 40px;">保存
                </el-button>
            </el-form-item>
        </el-form>
    </div>

</template>

<script setup>
// do not use same name with ref
import { Delete, Download, Plus, ZoomIn } from '@element-plus/icons-vue'
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { onBeforeUnmount, ref, shallowRef, onMounted, reactive } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { useRouter, useRoute } from 'vue-router';
import usePraStore from '../../store/pra'
import dayJS from 'dayjs'
import { ElMessage } from 'element-plus';


const store = usePraStore()
const { addPra } = store
const router = useRouter()
const route = useRoute()
const mode = ref('default')
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const disabled = ref(false)

const ruleFormRef = ref()


const imageUrl = ref('')
const handleRemove = (file) => {
    console.log(file)
}

const handlePictureCardPreview = (file) => {
    dialogImageUrl.value = file.url
    dialogVisible.value = true
}

const handleDownload = (file) => {
    console.log(file)
}
const test = reactive({
    title: '',
    image: '',
    intro: '',
    change: '',
    number: '',
    type: [],
    resource: '',
    desc: '',
    editor: '',
})



const beforeAvatarUpload = (rawFile) => {
    if (rawFile.type !== 'image/jpeg') {
        ElMessage.error('传入的图片格式不是jpg格式')
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('传入图片的大小不能超过2MB')
        return false
    }
    return true
}



//上传图片
const pic = ref()

const upload = (img) => {
    // console.log(img.url);
    pic.value = img.url

}



//富文本

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()

// 内容 HTML
const valueHtml = ref('<p>231</p>')

// 模拟 ajax 异步获取内容
onMounted(() => {
    setTimeout(() => {
        valueHtml.value = '<p></p>'
    }, 1500)
})

const toolbarConfig = {

    excludeKeys: [
        'fontSize',
        'fontFamily',
        'lineHeight',

    ]
}
const editorConfig = { placeholder: '请输入内容...' }

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
    const editor = editorRef.value
    if (editor == null) return
    editor.destroy()
})

const handleCreated = (editor) => {
    editorRef.value = editor // 记录 editor 实例，重要！
}

const Back = () => {
    router.back()
}


//保存

const onSubmit = (formEl) => {
    // console.log('submit!')
    // console.log(change.value);
    // console.log(test.title);
    // console.log(route.query.id);
    if (!formEl) return
    formEl.validate((valid) => {
        if (valid) {
            if (route.query.id) {
                const newpra = reactive({
                    id: route.query.id,
                    name: test.title,
                    content: test.intro,
                    checked: test.change,
                    sort: test.number,
                    advalue: valueHtml,
                    imgvalue: pic.value,
                    time: dayJS(new Date()).format("YYYY年MM月DD日")

                })
                console.log(123);
                store.addPra(newpra)
                router.push('/content/practice')
            } else {
                const newpra = reactive({
                    id: Math.ceil(Math.random() * 1000),
                    name: test.title,
                    content: test.intro,
                    checked: test.change,
                    sort: test.number,
                    advalue: valueHtml,
                    imgvalue: pic.value,
                    time: dayJS(new Date()).format("YYYY年MM月DD日")

                })
                store.addPra(newpra)
                router.push('/content/practice')
            }
        } else {
            ElMessage.error('提交失败')
            return false
        }
    })

}


// console.log(newpra);
// store.addPra(newpra)

// router.push('/content/practice')



const bianji = () => {
    //编辑
    // console.log(route.query.id);
    const res = store.pra.find(item => {
        return item.id == route.query.id
    })
    // console.log(res);

    test.title = res.name
    test.change = res.checked
    test.intro = res.content
    test.number = res.sort
    // valueHtml = res.advalue

}
if (route.query.id) {
    bianji()
}


const rules = reactive({
    title: [
        {
            required: true,
            message: '请输入标题',
            trigger: 'blur',
        }
    ],
    intro: [
        {
            required: true,
            message: '请输入简介',
        }
    ],
    change: [
        {
            required: true,
            message: '请选择是否推荐到首页',
        }
    ],
    number: [
        {
            required: true,
            message: '请输入排序位',
        }
    ],
})
</script>


<style  lang="less" scoped>
.header {
    width: 100%;
    height: 40px;
    padding: 5px;
    color: rgb(255, 153, 0);
    line-height: 30px;
    display: flex;
    justify-content: space-between;
    align-content: center;

    span {
        display: inline-block;
        width: 100px;
        font-weight: 900;
        height: 26px;
    }
}

.line {
    height: 10px;
    width: 100%;
    background-color: rgb(246, 239, 239);
}


.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}

// 富文本样式
#editor—wrapper {
    border: 1px solid #ccc;
    z-index: 100;
    /* 按需定义 */
}

#toolbar-container {
    border-bottom: 1px solid #ccc;
}

#editor-container {
    height: 500px;
}
</style>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>